package com.yunding.house.utils.wx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;

import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.yunding.house.pojo.User;
import com.yunding.house.pojo.Wxuser;
import com.yunding.house.service.IWxuserService;
import com.yunding.house.service.UserService;
import com.yunding.house.utils.wx.utils.SigUtils;
import com.yunding.house.utils.wx.utils.WeiXinUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Javen
 * 2015年12月5日下午2:20:44
 *
 */
@Controller
//@RequestMapping("/wxindex")
public class WeiXinOauthController extends ApiController{
    static Log log = Log.getLog(WeiXinOauthController.class);

    @Autowired
    private IWxuserService iWxuserService;
    @Autowired
    private UserService userService;

    /**
     * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
     * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
     */
//    @Before({})
    public ApiConfig getApiConfig() {
        ApiConfig ac = new ApiConfig();
        PropKit.use("javen_config.txt");
        // 配置微信 API 相关常量
        ac.setToken(PropKit.get("token"));
        ac.setAppId(PropKit.get("appId"));
        ac.setAppSecret(PropKit.get("appSecret"));

        /**
         *  是否对消息进行加密，对应于微信平台的消息加解密方式：
         *  1：true进行加密且必须配置 encodingAesKey
         *  2：false采用明文模式，同时也支持混合模式
         */
        ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
        return ac;
    }

    @RequestMapping("/oauth")
    public String index() {
        PropKit.use("javen_config.txt");
//        String userName = PropKit.get("userName");
//        String email = PropKit.get("email");

        // Prop 配合用法
//        Prop p = PropKit.use("config.txt");
//        Boolean devMode = p.getBoolean("devMode");

        int  subscribe=0;
        //用户同意授权，获取code
        String code=getPara("code");
        String state=getPara("state");
        if (code!=null) {
            String appId=PropKit.get("appId");
            String secret=PropKit.get("appSecret");
            //通过code换取网页授权access_token
            SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appId,secret,code);
//			String json=snsAccessToken.getJson();
            String token=snsAccessToken.getAccessToken();
            String openId=snsAccessToken.getOpenid();
            //拉取用户信息(需scope为 snsapi_userinfo)
            ApiResult apiResult=SnsApi.getUserInfo(token, openId);

            log.warn("getUserInfo:"+apiResult.getJson());
            if (apiResult.isSucceed()) {
                JSONObject jsonObject=JSON.parseObject(apiResult.getJson());
                String nickName=jsonObject.getString("nickname");
                //用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
                int sex=jsonObject.getIntValue("sex");
                String city=jsonObject.getString("city");//城市
                String province=jsonObject.getString("province");//省份
                String country=jsonObject.getString("country");//国家
                String headimgurl=jsonObject.getString("headimgurl");
                String unionid=jsonObject.getString("unionid");
                //获取用户信息判断是否关注
                ApiResult userInfo = UserApi.getUserInfo(openId);
                log.warn(JsonKit.toJson("is subsribe>>"+userInfo));
                if (userInfo.isSucceed()) {
                    String userStr = userInfo.toString();
                    subscribe=JSON.parseObject(userStr).getIntValue("subscribe");
                }
                Wxuser wxuser = new Wxuser();
                wxuser.setOpenId(openId);wxuser.setNickName(WeiXinUtils.filterWeixinEmoji(nickName));
                wxuser.setUnionid(unionid);wxuser.setHeadimgurl(headimgurl);
                wxuser.setCountry(country);wxuser.setCity(city);
                wxuser.setProvince(province);wxuser.setSex(sex==(1) ? "男" : "女");

                iWxuserService.save(wxuser);
            }
            setSessionAttr("openId", openId);

//            getSessionAttr("openid");
            if (subscribe==0) {
                redirect(PropKit.get("subscribe_rul"));
            }else {
                User user = userService.selectByopenid(openId);
                //根据state 跳转到不同的页面
                if (state.equals("user") && user!=null) {
                    //跳转首页
                    return  "forward:select.do?code=200&status=ok!";
//                    redirect("http://www.baidu.com/");
                }else {
                    //跳转注册页
                    redirect("/login");
                }
            }

        }else {
            renderText("code is  null");
        }
        return "";
    }

    /**
     * PC扫码登陆回调
     * 获取AccessToken以及用户信息跟微信公众号授权用户用户信息一样
     */
    public void webCallBack() {
        //用户同意授权，获取code
        String code=getPara("code");
        String state=getPara("state");
        if (code!=null) {
            System.out.println("code>"+code+" state>"+state);
            String appId=PropKit.get("webAppId");
            String secret=PropKit.get("webAppSecret");
            //通过code换取网页授权access_token
            SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appId,secret,code);
            String json=snsAccessToken.getJson();
            System.out.println("通过code获取access_token>>"+json);
            String token=snsAccessToken.getAccessToken();
            String openId=snsAccessToken.getOpenid();
            //拉取用户信息(需scope为 snsapi_userinfo)
            ApiResult apiResult=SnsApi.getUserInfo(token, openId);

            log.warn("getUserInfo:"+apiResult.getJson());
            if (apiResult.isSucceed()) {
                JSONObject jsonObject=JSON.parseObject(apiResult.getJson());
                String nickName=jsonObject.getString("nickname");
                //用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
                int sex=jsonObject.getIntValue("sex");
                String city=jsonObject.getString("city");//城市
                String province=jsonObject.getString("province");//省份
                String country=jsonObject.getString("country");//国家
                String headimgurl=jsonObject.getString("headimgurl");
                String unionid=jsonObject.getString("unionid");
            }
            renderText("通过code获取access_token>>"+json+"  \n"+"getUserInfo:"+apiResult.getJson());
        }

    }


    /**
     * 获取数据用于验证
     * @param request ：数据获取
     * @param
     */
    @RequestMapping(value = "/wx",method ={RequestMethod.GET})
    public @ResponseBody
    String VerificationToXeixin(HttpServletRequest request){

        //获取请求所发过来的数据
        String signature=request.getParameter("signature");
        String timestamp=request.getParameter("timestamp");
        String nonce=request.getParameter("nonce");
        String echostr=request.getParameter("echostr");

        //进行验证是否接入成功
        if(SigUtils.checkSignature(signature,timestamp,nonce)){
            System.out.println("success!");
            return echostr;
        }else{
            System.out.println("error！");
        }
        return null;
    }

}
